package demo.Thread;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/10-08-10-20:04
 * @Description：demo.Thread
 */
/*
设计4个线程，其中两个线程每次对 j 增加1，另外两个线程对 j 每次减少1。
 */
public class test_thread {
    static test_thread obj = new test_thread();
    static class inc implements Runnable{
        @Override
        public void run() {
            while(true){
                synchronized (obj){
                    if(obj.j < 1){
                        obj.j = obj.j + 1;
                        System.out.println(Thread.currentThread().getName() + ": " + obj.j);
                    }else{
                        try {
                            obj.notifyAll();
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    static class dec implements Runnable{
        @Override
        public void run() {
            while (true){
                synchronized (obj){
                    if(obj.j > 0){
                        obj.j = obj.j - 1;
                        System.out.println(Thread.currentThread().getName() + ": " + obj.j);
                    }else{
                        obj.notifyAll();
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    int j = 0;
    public static void main(String[] args) {
        inc th1 = new inc();
        Thread thread1 = new Thread(th1);
        Thread thread2 = new Thread(th1);

        dec th2 = new dec();
        Thread thread3 = new Thread(th2);
        Thread thread4 = new Thread(th2);

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}
